<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader
    @addTask="addTaskFn"
     :list="list"
    @checkAll="checkAll" ></TodoHeader>
    <TodoMain :list="showList" @del="delFn" @change="changeFn"></TodoMain>
    <TodoFooter :list="list"
     @clear="clearFn"
     :type="type"
     @changeType="changeTypeFn"
    ></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css"
import "./styles/index.css"
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";


export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      // 默认从本地取值
      list: JSON.parse(localStorage.getItem('todolist')) || [],
      type:'all' //all表示全部，yes表示完成，no表示未完成
    };
  },
  computed:{
    showList(){
      if(this.type === 'yes'){//显示已经完成
        return this.list.filter(item => item.isDone)
      }else if(this.type ==='no'){//显示未完成
        return this.list.filter(item => !item.isDone)
      }else{
        return this.list//显示全部
      }
    }
  },
  methods:{
    delFn(id){
      // console.log('触发了delFn',id);
      this.list=this.list.filter(item => item.id !== id)
    },
    changeFn(id){
      // console.log(id);
      const res = this.list.find(item => item.id === id)
      //遍历数组，有符合的元素就返回
      res.isDone = !res.isDone
    },
    addTaskFn(task){
      console.log('addTask',task);
      this.list.push({
        id:this.list.length ? this.list.at(-1).id + 1 : 100,
        name:task,
        isDone: false
      })
    },
    clearFn(){
      console.log('清空');
      // 触发App.vue里事件对应clear方法
      this.list = this.list.filter(item => item.isDone === false)
    },
    changeTypeFn(type){
      // 切换筛选条件
      // 子 -> 父 把类型字符串传给App.vue
      this.type = type
    },
   checkAll(val){
  // console.log('checkAll',val);
  this.list.forEach(item => item.isDone = val  )
   }
  },
  watch:{
    list:{
      deep:true,
      handler(newVal){//只要list变化，覆盖式保存到本地去
        localStorage.setItem('todolist',JSON.stringify(newVal))
      }
    }
  }
};
</script>